import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { getUserLoginInfo } from "@/utils/http/auth";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "",
    component: () => import("../views/home.vue"),
    meta: {
      title: "车牌预警",
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

/** 路由白名单 **/
const whiteList = ["/login"];

// 路由拦截
router.beforeEach((to, _from, next) => {
  /** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
  function toCorrectRoute() {
    whiteList.includes(to.fullPath) ? next(_from.fullPath) : next();
  }

  const userLoginInfo = getUserLoginInfo();
  /*****暂时去掉路由的拦截*****/
  next();
  /*****暂时去掉路由的拦截*****/

  if (
    userLoginInfo &&
    userLoginInfo?.tokenData?.access_token &&
    userLoginInfo?.tokenData?.expires_in > Date.now()
  ) {
    toCorrectRoute();
  } else {
    if (to.path !== "/login") {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next({ path: "/login" });
      }
    } else {
      next();
    }
  }
});

export default router;
